'use strict';
const db = uniCloud.database();
var ip = '';
var _appId = ''
var _wxPayKey = ''
var _wxPayMchId = ''
var isMiniApp = ''
var _appIdApp = ''
module.exports = {
	/**
	 * 此函数名称
	 * @url user/pub/test1 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		// 可写与数据库的交互逻辑等等

		let {
			openid,
			ip,
			total_offer,
			attach,
			isMiniApp
		} = data;
		const appIds = await db.collection('wx_config').where({
			'key': 'wxAppidApp'
		}).get()
		const appIdsApp = await db.collection('wx_config').where({
			'key': 'wxIdApp'
		}).get()
		const wxPayKey = await db.collection('wx_config').where({
			'key': 'wxPayKey'
		}).get()
		const wxPayMchId = await db.collection('wx_config').where({
			'key': 'wxPayMchId'
		}).get()

		_appId = appIds.data[0].val
		_wxPayMchId = wxPayMchId.data[0].val
		_wxPayKey = wxPayKey.data[0].val
		_appIdApp = appIdsApp.data[0].val

		if (!_appId && isMiniApp) {
			return {
				success: false,
				msg: '需要配置appid'
			}
		}
		if (!_appIdApp && !isMiniApp) {
			return {
				success: false,
				msg: '需要配置appid'
			}
		}
		if (!_wxPayMchId) {
			return {
				success: false,
				msg: '需要配置微信商户ID'
			}
		}
		if (!_wxPayKey) {
			return {
				success: false,
				msg: '需要配置微信商户密钥'
			}
		}
		let data1 = await wechat({
			"pid": getWxPayOrdrID(), //自定义的订单编号
			"attach": attach, //'支付的备注数据'
			"openid": openid, //用户的openid，为微信小程序时必须提供
			"isMiniApp": isMiniApp, //是否为微信小程序
			"total_offer": Number((Number(total_offer) * 100).toFixed(2)), //订单金额-单位为分
		});
		if (data1[0]) {
			return {
				"code": 0,
				"data": data1[1]
			};
		} else {
			return {
				"code": 1001,
				"data": data1[0]
			};
		}



		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}

async function wechat(e) {
	console.log(e, '1111111111111')
	const {
		pid,
		openid,
		isMiniApp,
		attach,
		total_offer
	} = e;
	//1.配置应用id
	var WX_APPID;
	if (isMiniApp) {
		WX_APPID = _appId;

	} else {
		WX_APPID = _appIdApp //app和h5等均使用 微信开放平台的appid
	}

	//2.配置微信支付KEY签名密钥
	var WX_KEY = _wxPayKey;
	//3.配置微信支付商户id
	var WX_MCHID = _wxPayMchId;




	const arrOrder = {};
	if (isMiniApp) {
		arrOrder['trade_type'] = 'JSAPI';
		arrOrder['openid'] = openid;
	} else {
		arrOrder['trade_type'] = 'APP';
	}
	console.log(WX_APPID, '12121')
	arrOrder['appid'] = WX_APPID; //微信支付应用id
	arrOrder['mch_id'] = WX_MCHID; //商户编号
	arrOrder['nonce_str'] = uniqid(); //随机字符串
	arrOrder['body'] = attach; //商品描述
	arrOrder['out_trade_no'] = pid; //订单编号
	arrOrder['attach'] = attach; //附加数据
	arrOrder['total_fee'] = total_offer; //订单金额-单位为分
	arrOrder['spbill_create_ip'] = ip; //客户端ip地址
	arrOrder['notify_url'] = 'https:wwww.baidu.com'; //回调url，unicloud生成方式参考 https://ext.dcloud.net.cn/plugin?id=1360
	arrOrder['sign'] = makeSign(arrOrder, WX_KEY); //签名
	let xml = toXml(arrOrder); //json转换成xml
	//和微信进行接口通信获取支付信息
	let url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
	let res = await httpPost(url, xml);
	console.log(res)
	//将结果转换为数数组
	var resArr = await xmlToJson(res.data);
	//判断通信结果
	if (resArr['return_code'] == 'FAIL') {
		return [0, resArr['return_msg']];
	}
	if (resArr['return_code'] == 'FAIL' || resArr['result_code'] == 'FAIL') {
		return [0, resArr['err_code_des']];
	}
	var arrPay = {};
	//var_dump(resArr);
	//统一下单接口返回正常的prepay_id，再按签名规范重新生成签名后，将数据传输给APP。
	if (isMiniApp) {
		arrPay['appId'] = WX_APPID;
		arrPay['timeStamp'] = new Date().getTime();
		arrPay['nonceStr'] = resArr['nonce_str'];
		arrPay['package'] = 'prepay_id=' + resArr['prepay_id'];
		arrPay['signType'] = 'MD5';

	} else {
		arrPay['appid'] = WX_APPID;
		arrPay['partnerid'] = WX_MCHID;
		arrPay['prepayid'] = resArr['prepay_id'];
		arrPay['noncestr'] = resArr['nonce_str'];
		arrPay['package'] = 'Sign=WXPay';
		arrPay['timestamp'] = new Date().getTime();
	}
	let sign = makeSign(arrPay, WX_KEY);
	arrPay['sign'] = sign;
	//返回app端需要的json形式的数据用于唤起微信支付
	arrPay['total_offer'] = total_offer;
	return [1, arrPay];
}
//微信支付签名
function makeSign(array, WX_KEY) {
	array = ksort(array);
	var string = '';
	for (let k in array) {
		let v = array[k];
		if (k != "sign" && v != "" && !(typeof v == 'array')) {
			string = string + k + "=" + v + "&";
		}
	}

	string = string.substring(0, string.length - 1);
	//签名步骤二：在string后加入KEY
	string = string + "&key=" + WX_KEY;
	//签名步骤三：MD5加密
	const md5 = require('md5-node');
	string = md5(string);
	//签名步骤四：所有字符转为大写
	let result = string.toUpperCase();
	return result;
}
// 对象按照key排序
function ksort(o) {
	let sorted = {},
		keys = Object.keys(o);
	keys.sort();
	keys.forEach((key) => {
		sorted[key] = o[key];
	})
	return sorted;
}

function uniqid() {
	const md5 = require('md5-node');
	return md5(new Date().getTime());
}

function toXml(_json) {
	var xml = '<xml>';
	for (let key in _json) {
		let val = _json[key];
		if (
			typeof val == 'string' ||
			typeof val == 'number'
		) {
			xml = xml + "<" + key + ">" + val + "</" + key + ">";
		} else {
			xml = xml + "<" + key + "><![CDATA[" + val + "]]></" + key + ">";
		}
	}
	xml = xml + '</xml>';
	return xml;
}

function xmlToJson(xml) {
	var xmlParser = require('xml2js').Parser({
		explicitArray: false,
		ignoreAttrs: true
	})
	var promise = new Promise(function(resolve, reject) {
		xmlParser.parseString(xml, function(err, result) {
			resolve(result.xml);
		});
	});
	return promise;
}

async function httpPost(url, xml) {
	const res = await uniCloud.httpclient.request(url, {
		method: 'POST',
		data: xml,
		dataType: "text"
	})
	return res;
}


/* 商户订单编号*/
function getWxPayOrdrID() {
	var myDate = new Date();
	var year = myDate.getFullYear();
	var mouth = myDate.getMonth() + 1;
	var day = myDate.getDate();
	var hour = myDate.getHours();
	var minute = myDate.getMinutes();
	var second = myDate.getSeconds();
	var msecond = myDate.getMilliseconds(); //获取当前毫秒数(0-999)
	if (mouth < 10) {
		/*月份小于10  就在前面加个0*/
		mouth = String(String(0) + String(mouth));
	}
	if (day < 10) {
		/*日期小于10  就在前面加个0*/
		day = String(String(0) + String(day));
	}
	if (hour < 10) {
		/*时小于10  就在前面加个0*/
		hour = String(String(0) + String(hour));
	}
	if (minute < 10) {
		/*分小于10  就在前面加个0*/
		minute = String(String(0) + String(minute));
	}
	if (second < 10) {
		/*秒小于10  就在前面加个0*/
		second = String(String(0) + String(second));
	}
	if (msecond < 10) {
		msecond = String(String(0) + String(second));
	} else if (msecond >= 10 && msecond < 100) {
		msecond = String(String(0) + String(second));
	}

	var currentDate =
		String(year) +
		String(mouth) +
		String(day) +
		String(hour) +
		String(minute) +
		String(second) +
		String(msecond);
	return currentDate;
}
